package cn.t.rpc.core.codec.strategy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import cn.t.rpc.core.exception.TRpcCoreException;

/**
 * GZIP压缩策略(数据量很小时可能会影响性能-小数据量的字节数组压缩后会变大)
 * 
 * @author TMQ
 *
 */
public class GzipCompress extends CompressStrategy {

	private static final int BUFFER_SIZE = 1024 * 2;

	@Override
	public byte[] compress(byte[] bytes) {
		
		if (bytes == null) {
			throw new TRpcCoreException("数据流为空...");
		}
		
		try (ByteArrayOutputStream out = new ByteArrayOutputStream();
				GZIPOutputStream gzip = new GZIPOutputStream(out)) {
			gzip.write(bytes);
			gzip.flush();
			gzip.finish();
			return out.toByteArray();
		} catch (IOException e) {
			throw new TRpcCoreException("gzip压缩异常");
		}
	}

	@Override
	public byte[] decompress(byte[] bytes) {

		if (bytes == null) {
			throw new TRpcCoreException("数据流为空...");
		}

		try (ByteArrayOutputStream out = new ByteArrayOutputStream();
				GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
			byte[] buffer = new byte[BUFFER_SIZE];
			int n;
			while ((n = gunzip.read(buffer)) > -1) {
				out.write(buffer, 0, n);
			}
			return out.toByteArray();
		} catch (IOException e) {
			throw new TRpcCoreException("gzip解压异常");
		}
	}
}
